from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views.generic import ListView, DetailView

from blog.models import Article


def index(request, page_index=1):
    # page_size = settings.PAGE_SIZE  # 从settings.py中获取配置
    PAGE_SIZE = 5
    start_index = (page_index - 1) * PAGE_SIZE  # 根据页码计算当前页的开始索引

    # 获取分页数据
    article_qs = Article.objects.all()[start_index:start_index + PAGE_SIZE]
    # article_qs = Article.objects.all()

    if article_qs.count:
        # article_paginator = Paginator(article_qs, PAGE_SIZE)
        # article_qs = article_paginator.page(page_index)

        result_dict = {
            'status': 200,
            'page_index': page_index,
            'data': [build_article_base_info(article) for article in article_qs]
        }
    else:
        result_dict = {'status': 202}

    return JsonResponse(result_dict, json_dumps_params={'ensure_ascii': False})


def detail(request, id):  # blog/article_detail

    article = Article.objects.get(pk=id)

    article_dict = build_article_base_info(article)

    return JsonResponse(article_dict, json_dumps_params={'ensure_ascii': False})


"""
blog 应用业务处理逻辑
"""


def build_article_base_info(article):
    """
    构造Article信息
    :param article:
    :return:
    """
    return {
        'id': article.id,
        'title': article.title,
        'author': article.author,
        'abstract': article.abstract,
        'reply_num': article.reply_num,
        'read_num': article.read_num,
        'like_num': article.like_num,
    }

class Home(ListView):
    model = Article
    template_name = 'blog_index.html'

class Detail(DetailView):
    model = Article
    template_name = 'blog_detail.html'
    context_object_name = 'ar'

